﻿from flask import Flask, g, render_template, request,flash,redirect,url_for,Blueprint
import pymysql,json,datetime,json
# from .login.login import *
from .setting import *

from flask_cors import CORS
comment_blue = Blueprint('comment',__name__)


def json_encoder(obj):
    if isinstance(obj, datetime.datetime):
        return obj.strftime("%Y-%m-%d %X")
    elif isinstance(obj, datetime.date):
        return obj.strftime("%Y-%m-%d")
@comment_blue.route('/blog/comment/list')
# @login_required
def commentlist():
	if request.args.get('article'):like = request.args.get('article')
	else:like=''
	if request.args.get('page'):page = request.args.get('page')
	else:page=1
	if request.args.get('limit'):limit = request.args.get('limit')
	else:limit=10
	# print(like,page,limit)
	db = pymysql.connect(host=dbhost,user=dbuser,password=dbpassword,database=dbdatabase)
	cursor = db.cursor()
	sql = "SELECT * from blog_comment WHERE  article LIKE '%"+like+"%'  LIMIT "+str(limit) +" OFFSET " +str((int(page)-1)*int(limit))
	sqlcount = "SELECT count(*) from blog_comment  WHERE  article LIKE '%"+like+"%'"
	if printsql:print(sql)
	try:
		cursor.execute(sql)
		dataList1 = cursor.fetchall()
		# for row in dataList:
			# print(row)
		dataList=[]
		for i in range(len(dataList1)):
			dataList.append({'id':dataList1[i][0],'article':dataList1[i][1],'comment':dataList1[i][2],'createdAt':dataList1[i][3]})
		cursor.execute(sqlcount)
		count = cursor.fetchall()[0][0]
	except Exception as e:
		return "Error: unable to fetch data from blog_comment"+str(e)
	db.close()
	data={
			'msg': 'success',
			'code': 0,
			'page': {
				'totalCount': len(dataList),
				'pageSize': 10,
				'totalPage': 1,
				'currPage': 1,
				'list': dataList
				}
			}
	return json.dumps(data,default=json_encoder)
@comment_blue.route('/blog/comment/save',methods=['POST'])
# @login_required
def commentsave():
	if request.data:
		if printrequestdata:print(request.data)
		d=json.loads(str(request.data, 'UTF-8'))
		if 'article' in d.keys():article = d['article']
		else:article=''
		if 'comment' in d.keys():comment = d['comment']
		else:comment=''
		if 'createdAt' in d.keys():createdAt = d['createdAt']
		else:createdAt=''
	elif request.form:
		article = request.form['article']
		comment = request.form['comment']
		createdAt = request.form['createdAt']

	db = pymysql.connect(host=dbhost,user=dbuser,password=dbpassword,database=dbdatabase)
	cursor = db.cursor()
	sql = 'insert into blog_comment (article,comment,created_at) values('+"'"+str(article)+"',"+"'"+str(comment)+"',"+"'"+str(createdAt)+"')"
	if printsql:print(sql)
	try:
		cursor.execute(sql)
		db.commit()
	except Exception as e:
		db.rollback()
		return "Error: unable to save data from blog_comment"+str(e)
	db.close()
	
	data={
      'msg': 'success',
      'code': 0
    }
	return json.dumps(data,default=json_encoder)
@comment_blue.route('/blog/comment/update',methods=['POST'])
# @login_required
def commentupdate():
	if request.data:
		if printrequestdata:print(request.data)
		d=json.loads(str(request.data, 'UTF-8'))
		if 'id' in d.keys():id = d['id']
		else:id=''
		if 'article' in d.keys():article = d['article']
		else:article=''
		if 'comment' in d.keys():comment = d['comment']
		else:comment=''
		if 'createdAt' in d.keys():createdAt = d['createdAt']
		else:createdAt=''
	elif request.form:
		id = request.form['id']
		article = request.form['article']
		comment = request.form['comment']
		createdAt = request.form['createdAt']

	db = pymysql.connect(host=dbhost,user=dbuser,password=dbpassword,database=dbdatabase)
	cursor = db.cursor()
	cursor = db.cursor()
	sql ="UPDATE blog_comment SET article='"+str(article)+"',comment='"+str(comment)+"',created_at='"+str(createdAt)+"'"+ "WHERE id = '"+str(id)+"'"
	if printsql:print(sql)
	try:
		cursor.execute(sql)
		db.commit()
	except Exception as e:
		db.rollback()
		return "Error: unable to delete data from blog_comment"+str(e)
	db.close()

	data={
	  'msg': 'success',
	  'code': 0
	}
	return json.dumps(data,default=json_encoder)
@comment_blue.route('/blog/comment/delete',methods=['POST'])
# @login_required
def commentdelete():
	# print("content_type:", request.headers.get("content_type"))
	# print("data:", request.data)
	# print("data:", str(request.data, 'UTF-8'))
	# print("form:", request.form)
	# print("files:", request.files)
	if request.data:
		if printrequestdata:print(request.data)
		d=json.loads(str(request.data, 'UTF-8'))
		if 'id' in d.keys():id = d['id']
		else:id=''
	elif request.form:
		id = request.form['id']

	db = pymysql.connect(host=dbhost,user=dbuser,password=dbpassword,database=dbdatabase)
	cursor = db.cursor()
	sql ="DELETE FROM blog_comment WHERE id='"+str(id)+"'"
	if printsql:print(sql)
	try:
		cursor.execute(sql)
		db.commit()
	except Exception as e:
		db.rollback()
		return "Error: unable to delete data from blog_comment"+str(e)
	db.close()

	data={
	  'msg': 'success',
	  'code': 0
	}
	return json.dumps(data,default=json_encoder)
@comment_blue.route('/blog/comment/info')
@comment_blue.route('/blog/comment/info/<id>')#for update
# @login_required
def commentinfo(id=None):
	db = pymysql.connect(host=dbhost,user=dbuser,password=dbpassword,database=dbdatabase)
	cursor = db.cursor()
	sql ="SELECT * from blog_comment where  id='"+str(id)+"'"
	if printsql:print(sql)
	try:
		cursor.execute(sql)
		dataList1 = cursor.fetchall()
		# for row in dataList:
			# print(row)
		comment={'id':dataList1[0][0],'article':dataList1[0][1],'comment':dataList1[0][2],'createdAt':dataList1[0][3]}
		data={
				'msg': 'success',
				'code': 0,
				'comment': comment
				}
		return json.dumps(data,default=json_encoder)
	except Exception as e:
		return "Error: unable to fetch data from blog_comment"+str(e)
	db.close()
@comment_blue.route('/blog/comment/select') #for other talbe's selector
# @login_required
def commentselect():
	db = pymysql.connect(host=dbhost,user=dbuser,password=dbpassword,database=dbdatabase)
	cursor = db.cursor()
	sql = "SELECT * from blog_comment"
	if printsql:print(sql)
	try:
		cursor.execute(sql)
		dataList1 = cursor.fetchall()
		# for row in dataList1:
			# print(row)
		dataList=[]
		for i in range(len(dataList1)):
			dataList.append({'id':dataList1[i][0],'article':dataList1[i][1],'comment':dataList1[i][2],'createdAt':dataList1[i][3]})
		# print(dataList)
		data={
				'msg': 'success',
				'code': 0,
				'list': dataList
				}
		return json.dumps(data,default=json_encoder)
	except Exception as e:
		return "Error: unable to fetch data from sys_role"+str(e)
	db.close()	
	
	
	


